<template>
	<view class="meal-container">
		<view class="header">
			<view class="back-btn" @tap="goBack">
				<text class="iconfont icon-back"></text>
			</view>
			<view class="title">{{mealTypeText}} ({{formatDate}})</view>
			<view class="add-btn" @tap="addFood">
				<text class="iconfont icon-add"></text>
			</view>
		</view>
		
		<view class="content">
			<!-- 当前餐次的食物列表 -->
			<view class="food-list" v-if="mealRecords.length > 0">
				<view class="food-item" v-for="(item, index) in mealRecords" :key="index">
					<image :src="item.foodImage || '/static/images/placeholder.png'" mode="aspectFill" class="food-image"></image>
					<view class="food-info">
						<view class="food-name">{{item.foodName}}</view>
						<view class="food-quantity">{{item.quantity || item.amount || 0}}{{item.foodUnit || 'g'}}</view>
						<view class="food-nutrition">
							<text class="nutrition-item">{{item.calories}}kcal</text>
							<text class="nutrition-item">碳水{{item.carbs || item.carbohydrate || 0}}g</text>
							<text class="nutrition-item">蛋白{{item.protein || 0}}g</text>
							<text class="nutrition-item">脂肪{{item.fat || 0}}g</text>
						</view>
					</view>
					<view class="food-actions">
						<view class="action-btn delete" @tap="deleteFood(item)">
							<text class="iconfont icon-delete"></text>
						</view>
					</view>
				</view>
				
				<!-- 营养摄入总结 -->
				<view class="nutrition-summary">
					<view class="summary-title">营养摄入总计</view>
					<view class="summary-content">
						<view class="summary-item">
							<text class="summary-label">卡路里</text>
							<text class="summary-value">{{totalCalories}}kcal</text>
						</view>
						<view class="summary-item">
							<text class="summary-label">碳水</text>
							<text class="summary-value">{{totalCarbs}}g</text>
						</view>
						<view class="summary-item">
							<text class="summary-label">蛋白质</text>
							<text class="summary-value">{{totalProtein}}g</text>
						</view>
						<view class="summary-item">
							<text class="summary-label">脂肪</text>
							<text class="summary-value">{{totalFat}}g</text>
						</view>
					</view>
				</view>
			</view>
			
			<!-- 空状态 -->
			<view class="empty-state" v-else>
				<image src="/static/images/empty.png" mode="aspectFit" class="empty-image"></image>
				<text class="empty-text">暂无{{mealTypeText}}记录</text>
				<view class="add-food-btn" @tap="addFood">添加食物</view>
			</view>
		</view>
	</view>
</template>

<script setup>
	import { ref, computed, onMounted, watch, onUnmounted } from 'vue'
	import { getDietRecords, getDietRecordsByMealType, deleteDietRecord } from '@/common/api/diet.js'
	import { getUserInfo } from '@/common/utils/auth.js'
	
	// 页面参数
	const type = ref('') // 餐次类型：breakfast, lunch, dinner, snack
	const date = ref('') // 日期：yyyy-MM-dd
	
	// 餐次记录
	const mealRecords = ref([])
	
	// 餐次类型文本映射
	const mealTypeMap = {
		'breakfast': '早餐',
		'lunch': '午餐',
		'dinner': '晚餐',
		'snack': '加餐'
	}
	
	// 获取餐次类型文本
	const mealTypeText = computed(() => {
		return mealTypeMap[type.value] || '餐次'
	})
	
	// 格式化日期显示
	const formatDate = computed(() => {
		if (!date.value) return ''
		
		const parts = date.value.split('-')
		if (parts.length !== 3) return date.value
		
		return `${parts[0]}年${parts[1]}月${parts[2]}日`
	})
	
	// 计算营养总量
	const totalCalories = computed(() => {
		if (!mealRecords.value || mealRecords.value.length === 0) return 0
		return mealRecords.value.reduce((sum, item) => sum + parseFloat(item.calories || 0), 0).toFixed(0)
	})
	
	const totalCarbs = computed(() => {
		if (!mealRecords.value || mealRecords.value.length === 0) return 0
		return mealRecords.value.reduce((sum, item) => {
			// 兼容不同的字段名
			const carbValue = parseFloat(item.carbs || item.carbohydrate || 0);
			return sum + carbValue;
		}, 0).toFixed(1)
	})
	
	const totalProtein = computed(() => {
		if (!mealRecords.value || mealRecords.value.length === 0) return 0
		return mealRecords.value.reduce((sum, item) => sum + parseFloat(item.protein || 0), 0).toFixed(1)
	})
	
	const totalFat = computed(() => {
		if (!mealRecords.value || mealRecords.value.length === 0) return 0
		return mealRecords.value.reduce((sum, item) => sum + parseFloat(item.fat || 0), 0).toFixed(1)
	})
	
	// 初始化
	onMounted(() => {
		// 获取URL参数
		const query = uni.getSystemInfoSync().platform === 'mp-weixin' ? 
			getCurrentPages()[getCurrentPages().length - 1].options : 
			uni.getLaunchOptionsSync().query
		
		if (query) {
			type.value = query.type || 'breakfast'
			date.value = query.date || new Date().toISOString().split('T')[0]
		}
		
		loadData()
		
		// 监听页面显示事件
		uni.$on('mealPageShow', () => {
			console.log('meal页面重新显示，刷新数据');
			loadData();
		});
	})
	
	// 确保在组件销毁时取消事件监听
	onUnmounted(() => {
		uni.$off('mealPageShow');
	})
	
	// 定义页面显示生命周期函数
	// 注意：uni-app中使用defineExpose或defineEmits来处理生命周期
	defineExpose({
		onShow() {
			// 页面显示时触发数据刷新
			console.log('meal页面显示，刷新数据');
			loadData();
		}
	});
	
	// 加载数据
	const loadData = async () => {
		if (!type.value || !date.value) {
			console.error('缺少必要参数:', { type: type.value, date: date.value });
			uni.showToast({
				title: '参数错误',
				icon: 'none'
			});
			return;
		}
		
		uni.showLoading({
			title: '加载中...'
		});
		
		// 检查网络连接
		try {
			const networkStatus = await new Promise((resolve) => {
				uni.getNetworkType({
					success: (res) => resolve(res)
				});
			});
			
			console.log('当前网络状态:', networkStatus);
			
			if (networkStatus.networkType === 'none') {
				uni.hideLoading();
				uni.showToast({
					title: '网络连接不可用',
					icon: 'none'
				});
				return;
			}
		} catch (e) {
			console.warn('获取网络状态失败:', e);
		}
		
		try {
			// 获取用户信息和用户ID
			const userInfo = getUserInfo();
			console.log('获取到的用户信息:', userInfo);
			
			// 使用userInfo中的id，如果不存在则使用默认值6
			const userId = userInfo && userInfo.id ? userInfo.id : 6;
			console.log('使用的用户ID:', userId);
			
			// 构建请求参数
			const requestParams = {
				userId: userId,
				date: date.value,
				mealType: type.value
			};
			
			console.log('请求饮食记录参数:', requestParams);
			
			// 添加请求超时处理
			const requestPromise = getDietRecordsByMealType(requestParams);
			
			// 添加超时处理
			const timeoutPromise = new Promise((_, reject) => {
				setTimeout(() => reject(new Error('请求超时，请检查网络连接')), 15000);
			});
			
			// 使用Promise.race来处理超时
			const res = await Promise.race([requestPromise, timeoutPromise]);
			
			console.log('饮食记录API响应:', JSON.stringify(res).substring(0, 500));
			
			if (res.code === 0) {
				if (res.data) {
					// 检查records字段是否存在
					if (Array.isArray(res.data.records)) {
						mealRecords.value = res.data.records;
						console.log('获取到饮食记录数量:', mealRecords.value.length);
						
						// 检查数据结构
						if (mealRecords.value.length > 0) {
							console.log('第一条记录示例:', JSON.stringify(mealRecords.value[0]));
						} else {
							console.log('无饮食记录数据');
						}
					} else if (Array.isArray(res.data)) {
						// 如果直接返回了数组
						mealRecords.value = res.data;
						console.log('获取到饮食记录数量:', mealRecords.value.length);
						
						// 检查数据结构
						if (mealRecords.value.length > 0) {
							console.log('第一条记录示例:', JSON.stringify(mealRecords.value[0]));
						} else {
							console.log('无饮食记录数据');
						}
					} else if (res.data.meals && Array.isArray(res.data.meals)) {
						// 如果返回的是包含meals数组的对象
						mealRecords.value = res.data.meals;
						console.log('从meals数组获取到饮食记录数量:', mealRecords.value.length);
						
						// 检查数据结构
						if (mealRecords.value.length > 0) {
							console.log('第一条记录示例:', JSON.stringify(mealRecords.value[0]));
						} else {
							console.log('无饮食记录数据');
						}
					} else if (res.data.mealType !== undefined && res.data.foodName) {
						// 如果返回的是单个记录对象
						// 转换为数组格式
						mealRecords.value = [{
							id: res.data.id,
							foodId: res.data.foodId,
							foodName: res.data.foodName,
							calories: res.data.calories,
							carbs: res.data.carbohydrate,
							protein: res.data.protein,
							fat: res.data.fat,
							quantity: 100, // 默认数量
							foodUnit: 'g', // 默认单位
							foodImage: res.data.foodImage,
							mealType: res.data.mealType
						}];
						
						console.log('从单条记录创建数组，饮食记录数量:', mealRecords.value.length);
					} else {
						console.warn('返回数据不包含有效的records数组:', JSON.stringify(res.data));
						// 尝试处理可能的数据结构
						const possibleRecords = res.data.meals || res.data.dietRecords || res.data.items || [];
						if (Array.isArray(possibleRecords) && possibleRecords.length > 0) {
							mealRecords.value = possibleRecords;
							console.log('从其他字段获取到饮食记录:', possibleRecords.length);
						} else {
							mealRecords.value = [];
							console.warn('无法从响应中提取有效的记录数据');
							
							// 尝试打印完整的返回数据结构
							try {
								console.warn('数据结构:', Object.keys(res.data));
							} catch(e) {
								console.warn('无法分析数据结构');
							}
						}
					}
				} else {
					mealRecords.value = [];
					console.warn('API响应中无data字段:', JSON.stringify(res));
				}
			} else {
				mealRecords.value = [];
				console.warn('API返回错误:', JSON.stringify(res));
				
				// 显示API错误信息
				uni.showToast({
					title: res.msg || '加载数据失败',
					icon: 'none'
				});
			}
		} catch (e) {
			console.error('加载饮食记录失败:', e.message || e);
			
			// 增加更详细的错误日志
			if (e.errMsg) {
				console.error('错误详情:', e.errMsg);
			}
			
			if (e.stack) {
				console.error('错误堆栈:', e.stack);
			}
			
			mealRecords.value = [];
			uni.showToast({
				title: e.message || '加载失败，请检查网络连接',
				icon: 'none'
			});
		} finally {
			uni.hideLoading();
		}
	};
	
	// 添加食物
	const addFood = () => {
		uni.navigateTo({
			url: `/pages/diet/add?date=${date.value}&mealType=${type.value}`
		})
	}
	
	// 删除食物
	const deleteFood = (item) => {
		uni.showModal({
			title: '提示',
			content: '确定要删除这条记录吗？',
			success: async (res) => {
				if (res.confirm) {
					try {
						uni.showLoading({
							title: '删除中...'
						})
						
						const result = await deleteDietRecord({ id: item.id })
						
						if (result.code === 0) {
							uni.showToast({
								title: '删除成功',
								icon: 'success'
							})
							
							// 重新加载数据
							loadData()
						} else {
							uni.showToast({
								title: result.message || '删除失败',
								icon: 'none'
							})
						}
					} catch (e) {
						console.error('删除记录失败:', e)
						uni.showToast({
							title: '删除失败',
							icon: 'none'
						})
					} finally {
						uni.hideLoading()
					}
				}
			}
		})
	}
	
	// 返回上一页
	const goBack = () => {
		uni.navigateBack()
	}
</script>

<style lang="scss">
	.meal-container {
		min-height: 100vh;
		background-color: #f5f7fa;
		
		.header {
			display: flex;
			justify-content: space-between;
			align-items: center;
			padding: 20rpx;
			background-color: #fff;
			position: sticky;
			top: 0;
			z-index: 100;
			
			.back-btn, .add-btn {
				width: 60rpx;
				height: 60rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				
				.icon-back, .icon-add {
					font-size: 36rpx;
					color: #333;
				}
			}
			
			.title {
				font-size: 32rpx;
				font-weight: bold;
				color: #333;
			}
		}
		
		.content {
			padding: 20rpx;
			
			.food-list {
				background-color: #fff;
				border-radius: 12rpx;
				overflow: hidden;
				
				.food-item {
					display: flex;
					padding: 20rpx;
					border-bottom: 1px solid #f0f0f0;
					
					.food-image {
						width: 120rpx;
						height: 120rpx;
						border-radius: 8rpx;
						margin-right: 20rpx;
						background-color: #f0f0f0;
					}
					
					.food-info {
						flex: 1;
						
						.food-name {
							font-size: 30rpx;
							font-weight: bold;
							color: #333;
							margin-bottom: 6rpx;
						}
						
						.food-quantity {
							font-size: 26rpx;
							color: #666;
							margin-bottom: 10rpx;
						}
						
						.food-nutrition {
							display: flex;
							flex-wrap: wrap;
							
							.nutrition-item {
								font-size: 24rpx;
								color: #888;
								margin-right: 20rpx;
								margin-bottom: 6rpx;
							}
						}
					}
					
					.food-actions {
						display: flex;
						flex-direction: column;
						justify-content: center;
						
						.action-btn {
							width: 60rpx;
							height: 60rpx;
							display: flex;
							align-items: center;
							justify-content: center;
							
							.iconfont {
								font-size: 36rpx;
							}
							
							&.delete {
								color: #ff6b6b;
							}
						}
					}
				}
				
				.nutrition-summary {
					padding: 20rpx;
					
					.summary-title {
						font-size: 28rpx;
						font-weight: bold;
						color: #333;
						margin-bottom: 15rpx;
					}
					
					.summary-content {
						display: flex;
						flex-wrap: wrap;
						
						.summary-item {
							width: 50%;
							margin-bottom: 10rpx;
							
							.summary-label {
								font-size: 26rpx;
								color: #666;
								margin-right: 10rpx;
							}
							
							.summary-value {
								font-size: 26rpx;
								font-weight: bold;
								color: #333;
							}
						}
					}
				}
			}
			
			.empty-state {
				display: flex;
				flex-direction: column;
				align-items: center;
				justify-content: center;
				padding: 100rpx 0;
				
				.empty-image {
					width: 240rpx;
					height: 240rpx;
					margin-bottom: 20rpx;
				}
				
				.empty-text {
					font-size: 28rpx;
					color: #999;
					margin-bottom: 40rpx;
				}
				
				.add-food-btn {
					padding: 16rpx 40rpx;
					background-color: #8cc9a1;
					color: #fff;
					font-size: 28rpx;
					border-radius: 50rpx;
				}
			}
		}
	}
</style> 